<template>
    <div style="width: 100%;height:100%;">
        <bpm-header :title="bpmInst.subject" :version="bpmInst.version" :user="bpmInst.createBy"></bpm-header>
        <div class="bpm-task-content">
            <a-tabs class="rx-a-tabs" default-active-key="details" @change="changeTabs($event)">
                <template #rightExtra>
                  <div class="tabs-toolbar">
                    <bpm-detail-buttons :curVm="getCurVm()" :bpmActionType="'bpmInstDetail'"></bpm-detail-buttons>
                  </div>
                </template>
                <a-tab-pane key="details" :tab="i18n('list.detail', '详情')">
                    <div class="tab-center-bg">
                        <div class="tab-center-content" >
                            <div class="tab-center-content-box" :class="{'tab-center-content-show':show}">
                                <div class="tab-center" >
                                    <bpm-inst-info v-if="bpmInst" :bpmInst="bpmInst"/>

                                    <rx-forms ref="rxForms" v-if="processConfig.formType=='online'"></rx-forms>
                                    <component v-else-if="processConfig.formType=='custom'"
                                               ref="customForm" :is="formComponent"
                                               :params="urlParamData"
                                               :pk="pk"></component>
                                    <url-view v-else-if="processConfig.formType=='outsideUrl'" ref="outSideUrlForm"   :pk="pk"
                                              :showUrl="outSideUrl" :urlParamData="urlParamData"></url-view>
                                </div>
                            </div>


                            <div class="bpm-history-button" @click="foldRight">
                                <rx-icon-show icon="iconVue3jpaas-icon_shenpilishi"></rx-icon-show>
                            </div>
                            <div class="bpm-task-history" :class="{'bpm-task-show':show}">
                                <!--审批历史-->

                                <div class="bpm-task-history-text">
                                    <span>{{i18n('list.appHistory', '审批历史')}}</span>
                                    <span class="bpm-history-close" @click="foldRight">
                                        <CloseOutlined />
                                    </span>
                                </div>
                                <bpm-history :inst-id="instId" v-model:historyShow="historyShow"/>
                            </div>
                        </div>
                    </div>
                </a-tab-pane>
                <a-tab-pane key="flowChart" :tab="i18n('list.flowChart', '流程图')" >
                    <bpm-image-view  v-if="isShowImage" :inst-id="instId" :preview="false" :formData="formData"></bpm-image-view>
                </a-tab-pane>
            </a-tabs>
            <ai-agent v-if="enableAi" :promptList="[]" :welcomeDescription="'有什么问题都可以向我提问~'" @fetchSuggestedQuestions="fetchSuggestedQuestions" @openParamsChange="openParamsChange" :incomingInfo="incomingInfo" :chatMessage="chatMessage" :questions="questions" />
        </div>
        <!-- 流程实例日志 -->
        <bpm-inst-logs :instId="instId" v-model:logShow="logShow"/>
        <!--流程实例消息-->
        <bpm-inst-msgs :instId="instId" v-model:msgShow="msgShow"/>

        <bpm-commu-history :inst-id="instId" v-model:bpmCommuShow="bpmCommuShow"/>
    </div>
</template>

<script>
import {RxDialog, Util, RxFit, TokenUtil,AiAgent} from '@lowcode/jpaas-base-lib';
import { App,BpmImageView } from '@lowcode/jpaas-share-component';
import BpmInstMsgs from "../components/BpmInstMsgs.vue"
import BpmInstLogs from "../components/BpmInstLogs.vue";
import BpmInstApi from '@/common/api/bpm/bpmInst'
import RxForms from "./RxForms.vue";
import BpmCommuHistory from "../components/BpmCommuHistory.vue";
import BpmInstInfo from "../components/BpmInstInfo.vue";
import formBase from './js/formBase.js';
import BpmInstTrackedApi from "@/common/api/bpm/bpmInstTracked";
import FlowUtil from "../js/FlowUtil.js";
import BpmTaskCommuApi from '@/common/api/bpm/bpmTaskCommu'
import bpmHeader from "./bpmHeader.vue";
import bpmHistory from "../components/bpmHistory.vue";
import useMain from "@/stores/useMain";
import userUser from "@/stores/userUser";
import { mapState } from 'pinia'

import BpmInstTransfer from "../components/BpmInstTransfer.vue";
import BpmInstTakeBack from "../components/BpmInstTakeBack.vue";
import BpmDetailButtons from "./BpmDetailButtons.vue";
import UrlView from "@/views/modules/form/FormCustomView/components/ColumnView/UrlView.vue";
import UrlParamsUtil from "@/views/modules/bpm/OpenDoc/js/url-params-util";
import AppUtil   from "@/assets/js/AppUtil";

export default {
    name: "BpmInstDetail",
    components: {
        AiAgent,
        UrlView,
        BpmDetailButtons,
        RxDialog,
        RxFit,bpmHistory,
        RxForms,
        BpmInstMsgs,
        BpmInstLogs,
        BpmCommuHistory,
        BpmInstInfo,
        BpmInstTransfer,
        BpmInstTakeBack,
        bpmHeader,BpmImageView
    },
    mixins: [formBase,FlowUtil,App,UrlParamsUtil],
    props: {
        layerid: {type: String},
        destroy: {type: Function},
        instId: {
            type: String,
            required: true
        },
        backNodeId: {//在流程明细中进行回退时指定的目标节点
            type: String,
            required: false
        },
        allowTransfer: {
            type: Boolean,
            required: false,
            default: false
        },
        allowTransReply: {
            type: Boolean,
            required: false,
            default: false
        },

        //来自页面(mydone:我完成的审批,mystart:我发起的流程)
        from: {
            type: String,
            default: ""
        }
    },
    computed: {
        ...mapState(useMain, ['appKey']),
        ...mapState(userUser, ['user']),
        trackedTheme() {
            return this.bpmInstDetail.tracked == '1' ? 'filled' : 'outlined';
        },
        trackText() {
            return this.bpmInstDetail.tracked == "1" ? this.i18n('list.tracked','已跟踪') : this.i18n('list.track','跟踪');
        },
        canTrack() {
            return this.bpmInst.status == "RUNNING" || this.bpmInst.status == 'REVOKE';
        },

        showMsgBtn(){
            let ary=['ARCHIVED'];
            if(ary.includes(this.bpmInst.status)){
                return false;
            }
            return true;
        }
    },
    data() {
        return {
            questions:[],
            incomingInfo:"",
            chatMessage:{
              url: "/api/api-bpm/bpm/core/bpmAi/calBpmAiApprove",
              body: {
                response_mode: "streaming"
              }
            },
            enableAi:false,
            historyShow: false,
            bpmCommuBtnShow: false,
            bpmCommuShow: false,
            logShow: false,
            msgShow: false,
            bpmInstDetail: {},
            bpmInst: {},
            processConfig: {
                buttons: [],
                startConfirm: false,
                fillOpinion: false,
                assignFlowUsers: false,
                startCalFlowusers: false,
                //是否允许选择路径。
                allowSelectPath: false,

                formType: "online",
                //开关
                switchOptions: []
            },
            buttons: [],
            pkId: "",
            formComponent: "",
            outSideUrl:"",
            urlParamData:[],
            urlParamsShow:false,
            pk: "",
            backBtnLoading: false,//撤回按钮加载状态
            //根实例
            rootVm: true,
            //是否可以撤回
            canRevoke: false,
            myStartBtn:[],
            //按钮loading
            btnLoading:false,
            show:true,
            formData:{},
            isShowImage:false
        }
    },
    created() {
        this.loadDetail();
        this.getCommuData();
    },
    methods: {
        async fetchSuggestedQuestions(messageId) {
          try {
            let token = TokenUtil.getToken();
            // 调用建议问题接口，示例需要根据实际API调整
            const response = await fetch("/api/api-bpm/bpm/core/bpmAi/suggested/"+messageId, {
              method: 'GET',
              headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
              }
            });

            const data = await response.json();
            this.questions = data || [];
          } catch (error) {
            console.error('获取建议问题失败:', error);
          }
        },
        openParamsChange(){
          let token = TokenUtil.getToken();
          this.chatMessage.header = {
            Authorization: `Bearer ${token}`,
            appId: this.$route.query.appId
          };
          this.chatMessage.body.formData = this.$refs.rxForms.getData();
          this.incomingInfo = this.bpmInstDetail.prompt;
        },
        getI18Name(item){
          if(item.i18nJson){
            return this.$i18(item.i18nJson,item.name)||item.name;
          }
          return item.name;
        },
        changeTabs(key){
            if(key=='flowChart'){
                this.getFormData();
            }else {
                this.isShowImage=false;
            }
        },
        getFormData(){
            this.formData = this.$refs.rxForms.getData();
            this.isShowImage=true;
        },
        foldRight(){
            this.show = !this.show
        },
        i18n(name,text,key){
            return this.$ti18(name,text,"bpmInst",key);
        },
        getCommuData() {
            if (!this.instId) {
                return;
            }
            let parameter = {
                instId: this.instId,
                taskId: "",
                nodeId: ""
            }
            BpmTaskCommuApi.getAllCommus(parameter).then(res => {
                if (!res.success) {
                    return;
                }
                let dataList = res.data;
                if(dataList.length>0){
                    this.bpmCommuBtnShow=true;
                }
            });
        },
        isBuildinBtn(btn) {
            var btns = ['btnTransfer', 'btnTransReply', 'btnBack', 'btnMessage','doDiscard', 'delInst','restoreInst','supspendInst'];
            return btns.indexOf(btn) > -1;
        },
        showCheckHistory() {
            this.historyShow = true;
        },
        doCommuHistory() {
            this.bpmCommuShow = true;
        },
        showBpmInstLog() {
            this.logShow = true;
        },
        showMsg() {
            this.msgShow = true;
        },
        retrieveTaskNode() {
            let self_ = this;
            Util.open({
                component: BpmInstTakeBack,
                curVm: this,
                widthHeight: ['600px', '320px'],
                title: self_.i18n('list.withdraw','撤回流程'),
                data: {
                    bpmInst: this.bpmInst,
                    from: this.from
                }
            }, function (action) {
                self_.loadDetail();
            });

        },
        //显示流程图
        showProcessImg() {
            Util.open({
                component: BpmImageView,
                curVm: this,
                widthHeight: ['1024px', '600px'],
                title: this.i18n('list.flowChart','流程图'),
                data: {
                    instId: this.instId,
                    formData: this.getFormData(),
                    preview: false
                }
            }, function (action) {
            });
        },
        loadDetail() {
            let self = this;
            if (!this.instId) {
                this.instId = this.$route.params.instId;
            }
            var self_ = this;
            BpmInstApi.getInstDetail(this.instId, this.from).then(res => {
                this.bpmInstDetail = res;
                this.enableAi = this.bpmInstDetail.enableAi;
                this.bpmInst = res.bpmInst;
                var contextData = {
                    curUserId: this.user.userId,
                    curUserName: this.user.fullName,
                    account: this.user.account,
                    type: "detail",
                    defId: res.bpmInst.defId,
                    instNo: res.bpmInst.instNo,
                    subject: res.bpmInst.subject,
                    instId: self.instId,
                    opinionHistorys: res.bpmCheckHistories,
                    //当前是否为发起人
                    starter:this.bpmInst.createBy==this.user.userId,
                };
                var config = Util.deepClone(self_.processConfig);
                self_.processConfig = Object.assign(config, res.processConfig);
                self_.buttons = self_.processConfig.buttonDetailConfigs;
                self_.canRevoke = res.canRevoke;
                self.pkId = res.bpmInst.busKey;
                var config = Util.deepClone(self.processConfig);
                self.processConfig = Object.assign(config, res.processConfig);

                this.handFormConfig(self.processConfig);

                if(self.processConfig.formType=='online') {
                  self.$nextTick(function () {
                    self.$refs.rxForms.setData(res.formData.data, true, contextData);
                  })
                }
                else{
                    //设置外部URL表单的主键
                    this.pk= this.bpmInst.busKey;
                    this.curData={pk:this.pk};
                }
                //暂停/恢复按钮
                if(self_.buttons && self_.buttons.length>0){
                    if(this.bpmInstDetail.bpmInst.status=="RUNNING"){
                        this.myStartBtn=['doDiscard', 'delInst','supspendInst'];
                    }else if(this.bpmInstDetail.bpmInst.status=="SUPSPEND") {
                        this.myStartBtn=['doDiscard', 'delInst','restoreInst'];
                    }else if(this.bpmInstDetail.bpmInst.status=="CANCEL") {
                        this.myStartBtn=['delInst'];
                    }
                }
            })
        },
        //处理表单配置。
        handFormConfig(conf) {
            //startForm
            let startForm = conf.detailForm.formpc;
            if (startForm && startForm.length > 0) {
                var form = startForm[0];
                this.handCustomForm(form);
            }
            //获取全局。
            let globalForm = conf.globalForm.formpc;
            if (globalForm && globalForm.length > 0) {
                var form = globalForm[0];
                this.handCustomForm(form);
            }
        },
        /**
         * 处理自定义表单和外部URL表单.
         * @param form
         */
        handCustomForm(form){
            let bpmInst = this.bpmInstDetail.bpmInst;
            let formId=form.id;
            if (form && form.type == "custom") {
                this.processConfig.formType = "custom";
                this.formComponent = AppUtil.loadComponent(form.component);
                this.handFormParams(formId,bpmInst);
            }
            if (form && form.type == "outsideUrl") {
                this.outSideUrl = form.component;
                this.processConfig.formType = "outsideUrl";
                this.handFormParams(formId,bpmInst);
            }
        },
        handFormParams(formId,bpmInst){
            var contextData={
                defId:bpmInst.defId,
                instId:bpmInst.instId,
                stageType: "detail",
            }
            this.handUrlParams(formId,contextData);
        },
        printForm() {
            var baseUrl = import.meta.env.JPAAS_BASE_URL;
            var appId=this.bpmInst.appId;
            var defId = this.bpmInst.defId;
            var instId = this.bpmInst.instId;
            var url = baseUrl ;
            if(baseUrl.includes('main')){
                url+="/flowPrint/" + defId;
            }else {
                url+="/" + this.appKey +"/flowPrint/" + defId;
            }

            if (instId) {
                url += "/" + instId;
            } else {
                url += "/-1";
            }
            if(appId){
                url+="?appId=" + appId;
            }
            window.open(url);
        },
        Ureport(name) {
            if (!this.pkId) {
                this.$message.warning(this.i18n('illegal','非法操作'));
                return;
            }
            var url = "/ureport/preview?_u=qiaolin-" + name + "&Id=" + this.pkId;
            window.open(url);
        },
        formPrint() {
            this.printForm();
        },
        close() {
            if (this.destroy) {
                Util.close(this, "cancel");
            } else {
                window.close();
            }
        },

        transferTo() {
            Util.open({
                component: BpmInstTransfer,
                curVm: this,
                widthHeight: ['800px', '500px'],
                title: this.i18n('forwardInst','转发流程实例') + this.bpmInst.subject,
                data: {
                    instId: this.instId,
                    send: true
                },
            }, function (action) {
                console.log(action)
            })
        },
        transferReply() {
            Util.open({
                component: BpmInstTransfer,
                curVm: this,
                widthHeight: ['800px', '500px'],
                title: this.i18n('replyFor','回复转发[') + this.bpmInst.subject + "]",
                data: {
                    instId: this.instId,
                    send: false
                },
            }, function (action) {
                console.log(action)
            })
        },
        doTracked() {
            let instId = this.bpmInst.instId;
            BpmInstTrackedApi.doTracked(instId).then(res => {
                this.bpmInstDetail.tracked = res.data;
            })
        },
        //我发起的流程 按钮
        isMyStartBtn(btn) {
            return this.from=='mystart' && this.myStartBtn.indexOf(btn) > -1;
        },
        //作废
        doDiscard(btn){
            let self_ = this;
            self_.btnLoading=true;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips','操作提示'),
                content: this.i18n('content.cancel','您确定需要作废当前流程吗？'),
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    BpmInstApi.cancelProcess(self_.instId,"作废").then(resp=> {
                        window.location.reload();
                    });
                },
                onCancel() {
                    self_.btnLoading=false;
                }
            })
        },
        //删除
        delInst(btn){
            let self_ = this;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips','操作提示'),
                content: this.$ti18('rxMsa.delInfo','您确定需要删除选中的记录吗？'),
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    BpmInstApi.delBpmInst({ ids: self_.instId }).then(res => {
                        window.close();
                    })
                },
                onCancel() {}
            })
        },
        //恢复
        restoreInst(btn){
            let self_ = this;
            self_.btnLoading=true;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips','操作提示'),
                content: this.i18n('content.restore','您确定需要恢复当前流程吗？'),
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    BpmInstApi.updateProcessStatus(self_.instId,'RUNNING').then(resp=> {
                        window.location.reload();
                    });
                },
                onCancel() {
                    self_.btnLoading=false;
                }
            })
        },
        //暂停
        supspendInst(btn){
            let self_ = this;
            self_.btnLoading=true;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips','操作提示'),
                content: this.i18n('content.suspend','您确定暂停当前流程吗？'),
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    BpmInstApi.updateProcessStatus(self_.instId,'SUPSPEND').then(resp=> {
                        self_.btnLoading=true;
                        window.location.reload();
                    });
                },
                onCancel() {
                    self_.btnLoading=false;
                }
            })
        },
        getCurVm(){
            return this;
        }
    }
}
</script>

<style scoped>
.tab-center ::v-deep(.x-form-build-box){
    margin: 0;
    overflow: initial;
}
.tab-center-bg{
    width: 100%;
    height: 100%;

    overflow: auto;
    position: relative;
}
.tabs-toolbar{
    height: 45px;
    display: flex;
    align-items: center;
}
.tab-center-content{
    display: inline-block;
    vertical-align: top;
    width: 100%;
    padding-bottom: 10px;
    background: #F5F5F5;
    position: relative;
}
.tab-center-content-box{
    transition: all .5s;
}
.tab-center-content-show{
    width: calc( 100% - 340px );
}

.tab-center{
    box-sizing: border-box;
    max-width: 1300px;
    width: 80%;
    margin: auto;
    min-height: calc( 100vh - 121px );
    background: #fff;
}
.bpm-task-history{
    vertical-align: top;
    display: flex;
    flex-direction: column;
    right: 0;
    top: 0;
    background-color: #fff;
    width: 0;
    opacity: 0;
    transition: all .5s;
    overflow: hidden;
    position: absolute;
    z-index: 11;
}
.bpm-history-button{
    top: 10px;
    right: 10px;
    position: absolute;
    width: 44px;
    height: 44px;
    background: #fff;
    box-shadow: 0 3px 10px 1px rgba(0,0,0,0.06);
    border-radius: 4px;
    z-index: 9;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}
.bpm-task-history-text{
    padding: 10px ;
    border-bottom: 1px solid #E8E8E8;
    font-size: 16px;
    color: #333;
    font-weight: bold;
    display: flex;
    justify-content: space-between;
}
.bpm-history-close{
    display: inline-block;
    padding:0 4px;
    cursor: pointer;
}
.bpm-history-close:hover{
    color: #4d9eff;
}
.bpm-task-show{
    width:340px ;
    opacity: 1;
}

.rx-a-tabs >>> .ant-tabs-bar.ant-tabs-top-bar{
    margin-bottom: 0!important;
}
.bpm-task-content{
    height: calc( 100% - 50px);
    background-color: #F5F5F5;
}

.rx-a-tabs{
    width: 100%;
    height: 100%;
}
.rx-a-tabs ::v-deep(.ant-tabs-nav){
    background-color: #fff;
    margin-bottom: 10px;
    padding-left: 20px;
}
.fitContainer {
    background: #fff;
    padding: 10px;
    padding-right: 0;
    box-sizing: border-box;
    height: 100%;
    width: 100%;
    overflow: auto;
}

.fitContainer .contents {
    background: #fff;
    border-radius: 6px;
    min-height: 100%;
    box-sizing: border-box;
    display: inline-block;
    width: 100%;
    max-width: 1300px;
    text-align: left;
    border: solid 1px #dadde0;
    position: relative;
}

.contentsStatus {
    position: absolute;
    z-index: 2;
    top: 0px;
    right: 10px;
}
</style>
